package com.example.makerspace.controller.socket;

import com.example.makerspace.config.WebSocketConfig;
import com.example.makerspace.dao.ImsingleDAO;
import com.example.makerspace.dao.OnlineUserListDAO;
import com.example.makerspace.domain.ChatMessage;
import com.example.makerspace.domain.ImsingleDO;
import com.example.makerspace.domain.OnlineUserListDO;
import com.example.makerspace.domain.UserDO;
import com.example.makerspace.service.ApplicationService;
import com.example.makerspace.service.CustomerService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;


import javax.annotation.Resource;
import javax.websocket.Session;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpSession;
import javax.websocket.EndpointConfig;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.OnClose;
import javax.websocket.server.ServerEndpoint;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint(value = "/chat/websocket",configurator= WebSocketConfig.class)
@Component
public class MyWebSocket {

    //用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();
    //用来记录username和该session进行绑定
    private static Map<String, Session> map = new HashMap<String, Session>();
    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;
    //用户名
    private String username;

    private  static  CustomerService customerService;

    private  static ImsingleDAO imsingleDAO;

    private  static OnlineUserListDAO onlineUserListDAO;


    @Resource
    public void setCustomerService(CustomerService customerService) {
        MyWebSocket.customerService = customerService;
    }

    @Resource
    public void setImsingleDAO(ImsingleDAO imsingleDAO) {
        MyWebSocket.imsingleDAO = imsingleDAO;
    }

    @Resource
    public void setOnlineUserListDAO(OnlineUserListDAO onlineUserListDAO) {
        MyWebSocket.onlineUserListDAO = onlineUserListDAO;
    }






    /**
     * 连接建立成功调用的方法，初始化昵称、session
     */
    @OnOpen
    public void onOpen(Session session, EndpointConfig config) {


        //获取登录时存放httpSession的用户数据
        HttpSession httpSession= (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        UserDO userDO = new UserDO();
        userDO.setUsername("3131");
        httpSession.setAttribute("user",userDO);

        UserDO user = (UserDO) httpSession.getAttribute("user");

        OnlineUserListDO onlineUserListDO = new OnlineUserListDO();

        BeanUtils.copyProperties(user,onlineUserListDO);
        //在线用户统计
        onlineUserListDAO.insert(onlineUserListDO);
        this.session = session;
        this.username = user.getUsername();


        //绑定username与session
        map.put(username, session);

        webSocketSet.add(this);     //加入set中

    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {

        //断开连接,删除在线用户数
        onlineUserListDAO.deleteByUserName(username);
        webSocketSet.remove(this);  //从set中删除

    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message) {

        //从客户端传过来的数据是json数据，所以这里使用jackson进行转换为chatMsg对象，
        ObjectMapper objectMapper = new ObjectMapper();
        ChatMessage chatMsg;

        try {
            try {
                chatMsg = objectMapper.readValue(message, ChatMessage.class);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }

            //对chatMsg进行装箱
            chatMsg.setFromUser(username);
            chatMsg.setSendTime(new Date());
            chatMsg.setLatest(true);

            Session fromSession = map.get(chatMsg.getFromUser());
            Session toSession = map.get(chatMsg.getToUser());

            //发送给接收者.
            fromSession.getAsyncRemote().sendText(username + "：" + chatMsg.getContent());

            ImsingleDO imsingleDO = new ImsingleDO();
            imsingleDO.setFromuser(username);
            imsingleDO.setTouser(chatMsg.getToUser());
            imsingleDO.setContent(chatMsg.getContent());
            imsingleDO.setReaded(0);
            imsingleDAO.insert(imsingleDO);

            if (toSession != null) {
                //发送给发送者.
                toSession.getAsyncRemote().sendText(username + "：" + chatMsg.getContent());
            }


        }catch (Exception e){
            System.out.println(e);
        }
    }


    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    /**
     * 群发自定义消息
     */
    public void broadcast(String message) {
        for (MyWebSocket item : webSocketSet) {

            //异步发送消息.
            item.session.getAsyncRemote().sendText(message);
        }
    }
}
